package com.tyylab.message.distribute.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tyylab.message.api.event.model.PingEvent;
import com.tyylab.message.core.config.properties.TyylabMessageRedisProperties;
import com.tyylab.message.core.model.TransMessage;
import com.tyylab.message.core.service.IChannelCheck;
import com.tyylab.message.core.service.ISyncPublish;
import com.tyylab.message.distribute.distribute.IChannelBuilder;
import com.tyylab.message.distribute.distribute.IChannelGetter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ScheduleTask {

    @Autowired
    TyylabMessageRedisProperties messageRedisPropertiesChannel;

    @Autowired
    IChannelBuilder channelBuilder;

    @Autowired
    ISyncPublish publish;

    @Autowired
    IChannelCheck channelCheck;

    @Autowired
    IChannelGetter channelGetter;

    final long minChannelSize = 10;

    @Autowired
    @Scheduled(fixedDelay = 1000 * 10) //每10s执行一次
    public void autoUpdate(){
        try {
            channelBuilder.build();
        }
        catch(Exception e){
            log.error(e.getMessage(),e);
        }
    }

    @Autowired
    @Scheduled(fixedDelay = 2000) //每1s执行一次
    public void globalping(){
        PingEvent event = PingEvent.builder().msg("ping").build();
        String json = JSON.toJSONString(event);
        JSONObject jsonObject =JSONObject.parseObject(json);
        TransMessage simulMessage = TransMessage.builder()
                .message(jsonObject)
                .clz(event.getClass().getName())
                .id(generateUUID())
                .build();

        for (String channel : getChannels(simulMessage)
             ) {
            publish.publish(simulMessage,channel);
        }

    }

    private List<String> getChannels(TransMessage simulMessage){
        String clzName = simulMessage.getClz();
        if (StringUtils.isBlank(clzName)){
            log.error("Message 错误，缺少Clz：" + JSON.toJSONString(simulMessage));
            return Lists.newLinkedList();
        }
        String curChannel = messageRedisPropertiesChannel.getChannel();
        Collection<String> channels = channelGetter.getTargetChannel(clzName);
        if (null == channels){
            channels = Lists.newLinkedList();
        }
        channels.add(curChannel);

        if (null != channels && !channels.isEmpty()) {
            List<String> targetChannel = Lists.newLinkedList();
            for (String channel :
                    channels) {
                if (channelCheck.sizeOf(channel) < minChannelSize){
                    targetChannel.add(channel);
                }
            }
            return targetChannel;
        }
        else{
            return Lists.newLinkedList();
        }
    }

    private static String generateUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-","");
    }

}
